import React, { createElement, useState } from 'react';
import { Comment, Tooltip, Avatar } from 'antd';
import moment from 'moment';
import { DislikeOutlined, LikeOutlined, DislikeFilled, LikeFilled } from '@ant-design/icons';
import {httpUpdatePostLikes, httpUpdatePostDislikes } from "../../apis";

import "./Post.scss"

export default function Post(props) {
  const post = props.post;

  const [likes, setLikes] = useState(post.likes);
  const [dislikes, setDislikes] = useState(post.dislikes);
  const [action, setAction] = useState(null);

  const like = async () => {
    if(action==="liked")return ;
    setLikes(likes+1);
    let data = {};
    data.likes = likes + 1;
    data.postId = post.postId;
    let res = await httpUpdatePostLikes(data);
    if(action) {
      setDislikes(dislikes-1);
      data.dislikes = dislikes - 1;
      await httpUpdatePostDislikes(data);
    }
    setAction('liked');
  };

  const dislike = async () => {
    if(action==="disliked")return ;
    setDislikes(dislikes+1);
    let data = {};
    data.dislikes = dislikes + 1;
    data.postId = post.postId;
    let res = await httpUpdatePostDislikes(data);
    if(action) {
      setLikes(likes-1);
      data.likes = likes - 1;
      await httpUpdatePostLikes(data);
    }
    setAction('disliked');
  };

  const actions = [
    <Tooltip key="comment-basic-like" title="Like">
      <span onClick={like}>
        {createElement(action === 'liked' ? LikeFilled : LikeOutlined)}
        <span className="comment-action">{likes}</span>
      </span>
    </Tooltip>,
    <Tooltip key="comment-basic-dislike" title="Dislike">
      <span onClick={dislike}>
        {React.createElement(action === 'disliked' ? DislikeFilled : DislikeOutlined)}
        <span className="comment-action">{dislikes}</span>
      </span>
    </Tooltip>,
    <span key="comment-basic-reply-to">Reply to</span>,
  ];
  return (
    <div className="Post-container">
      <Comment
        actions={actions}
        author={<a>{post.name}</a>}
        avatar={<Avatar src={post.url} alt="这是一个头像" />}
        content={
          <p>
            {post.content}
          </p>
        }
        datetime={
          <Tooltip title={moment(new Date()).format('YYYY-MM-DD HH:mm:ss')}>
            <span>{moment(new Date()).fromNow()}</span>
          </Tooltip>
        }
      />
    </div>

  )
}
